package cn.zhz.controller;

import cn.zhz.entity.User;
import cn.zhz.service.user.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
public class LoginController {
    private Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login.html",method = RequestMethod.GET)
    public String login(){
        logger.debug("跳转登录");
        return "login";
    }

    @RequestMapping(value = "/doLogin.html",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public String doLogin(@RequestParam String userCode,
                          @RequestParam String userPassword,
                          HttpSession session){
        logger.debug("验证登录");
        User user = userService.login(userCode,userPassword);
        if (null != user) {
            //匹配密码
            if(!user.getUserPassword().equals(userPassword)){
                throw new RuntimeException("密码输入错误！");
            }
            session.setAttribute("userSession",user);
            return "redirect:main.html";
        } else {
            throw new RuntimeException("用户名不存在！");
        }
    }

    @RequestMapping(value = "/main.html")
    public String main(){
        return "frame";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("error",e.getMessage());
        return "login";
    }
}
